package com.dc.common.utils;

import com.dc.common.exception.ServiceException;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuangcy
 * @date 2021/2/24
 * @description bean处理工具类
 */
public class BeanUtil extends BeanUtils {
    /**
     * 对象转Map
     *
     * @param object
     * @return
     */
    public static Map beanToMap(Object object) {
        return new BeanMap(object);
    }

    /**
     * map转对象
     *
     * @param map
     * @param beanClass
     * @param <T>
     * @return
     */
    public static <T> T mapToBean(Map map, Class<T> beanClass) {
        try {
            T object = beanClass.newInstance();
            populate(object, map);
            return object;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 对象转Map
     *
     * @param obj 转换对象
     * @return
     */
    public static Map<String, String> objectToMap(Object obj) {
        try {
            return describe(obj);
        } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return new HashMap<>(1);
    }

    /**
     * Bean属性复制工具方法。
     *
     * @param dest 复制对象
     * @param orig 被复制对象
     */
    public static void copyBeanProp(Object dest, Object orig) {
        try {
            copyProperties(dest, orig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
